package com.datamation.swadeshi.view;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.control.ConnectionDetector;
import com.datamation.swadeshi.control.DownloadTaskListener;
import com.datamation.swadeshi.control.Downloader;
import com.datamation.swadeshi.control.TaskType;
import com.datamation.swadeshi.control.data.DatabaseHelper;
import com.datamation.swadeshi.control.data.SalRepDS;
import com.datamation.swadeshi.control.data.ServerDatabaseDS;
import com.datamation.swadeshi.control.data.SharedPreferencesClass;
import com.datamation.swadeshi.model.ServerDatabase;

public class SplashActivity extends Activity implements DownloadTaskListener {

	private static String TAG="Swadeshi";
	private static ProgressDialog progressDialog;
	private static String spURL="";
    // Splash screen timer
    private static int SPLASH_TIME_OUT = 2000;
	DatabaseHelper db;
	SharedPreferences localSP;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		setContentView(R.layout.splash_activity);
		
		db=new DatabaseHelper(getApplicationContext());
		SQLiteDatabase YourDatabaseName;
		YourDatabaseName = db.getWritableDatabase();
		db.onUpgrade(YourDatabaseName, 1, 2);
		try {
			titleMethod();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		localSP = getSharedPreferences(SharedPreferencesClass.SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		if(!localSP.getString("URL", "").equals("")){
			
			
			 new Handler().postDelayed(new Runnable() {

					@Override
		            public void run() {
		                // This method will be executed once the timer is over
		                // Start your app main activity
						SalRepDS ds= new SalRepDS(getApplicationContext());
						if(!ds.getCurrentRepCode().equals("") && localSP.getString("Sync_Status", "").toString().equals("Success")){
							
							Intent mainActivity = new Intent(SplashActivity.this, LoginActivity.class);
					        startActivity(mainActivity);
					        
						}else{
							
							Intent mainActivity = new Intent(SplashActivity.this, SettingsActivity.class);
					        startActivity(mainActivity);
					        
						}
			            // close this activity
		                finish();
		            }
		        }, SPLASH_TIME_OUT);
			
		}else{
			//checking ip address of the server
			alertDialogbox(SplashActivity.this);
		}
        
	}//end oncreate()
	
	/**
	 * Title name method
	 */
	public void titleMethod() throws Exception{
			Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/fat_tats.ttf");
		 	//TextView tvTitle = (TextView) findViewById(R.id.spl_title);
		 	TextView tvVersion = (TextView) findViewById(R.id.spl_version);
	       // tvTitle.setText("FiNAC");
	       // tvTitle.setTypeface(tf);
	        
	        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
	        String version = pInfo.versionName;
	        tvVersion.setText("Version: "+version);
	        
	}//titleMethod()
	
	/**
	 * IP alert dialogbox
	 */
	private void alertDialogbox(final Context context){
		// get prompts.xml view
		LayoutInflater layoutInflater = LayoutInflater.from(context);

		View promptView = layoutInflater.inflate(R.layout.ip_connection, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		alertDialogBuilder.setTitle("Please enter server URL");
		// set prompts.xml to be the layout file of the alertdialog builder
		alertDialogBuilder.setView(promptView);

		final EditText input = (EditText) promptView.findViewById(R.id.et_ip);

		// setup a dialog window
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								//new PrefetchData().execute();
								boolean connectionStatus = new ConnectionDetector(SplashActivity.this).isConnectingToInternet();
								spURL=input.getText().toString().trim();
								String URL ="http://"+input.getText().toString().trim();
								
								if (Patterns.WEB_URL.matcher(URL).matches()){
								
									if(connectionStatus == true){
										String downLoadURL="/PDADBWebServiceM/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123";
										new Downloader(SplashActivity.this, SplashActivity.this, TaskType.DATABASENAME,URL,downLoadURL).execute();
										
									}else{
										
										Toast.makeText(SplashActivity.this, "No Internet Connection", Toast.LENGTH_LONG).show();
										reCallActivity();
									}
								}else{
									
									Toast.makeText(SplashActivity.this, "Invalid URL Entered. Please Enter Valid URL.", Toast.LENGTH_LONG).show();
									reCallActivity();
								}
								
							}
						})
						.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
								
								SplashActivity.this.finish();
							}
						});

		// create an alert dialog
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		 finish();
		
	}

	/**
     * Async Task to make http call
     */
    private class PrefetchData extends AsyncTask<String, Integer, Boolean> {
    	
    	int totalRecords=0;
    	
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(SplashActivity.this);
            progressDialog.setTitle("Prefetching data...");
            progressDialog.show();
        }
 
        @Override
        protected Boolean doInBackground(String... arg0) {
            
        	try {
        		int recordCount = 0;
        		String jsonLine= arg0[0];
				
        		ServerDatabaseDS ds =new ServerDatabaseDS(SplashActivity.this);
				ArrayList<ServerDatabase> list =new ArrayList<ServerDatabase>();
				JSONObject jsonResponse = new JSONObject(jsonLine);
				JSONArray jsonArray = jsonResponse.getJSONArray("GetdatabaseNamesResult");
				totalRecords=jsonArray.length();
				Log.v(TAG, "Array Length Server DB :" + jsonArray.length());
				for (int i = 0; i < jsonArray.length(); i++)
				{
				
					ServerDatabase serverDatabase =new ServerDatabase();
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					Log.v(TAG, "DB Name:  "+sdbname);
					
					serverDatabase.setDatabaseName(sdbname);
					list.add(serverDatabase);
					
					++recordCount;
					publishProgress(recordCount);
				}
				
				int db_result =ds.createOrUpdateServerDB(list);
				if(db_result>0){	
					return true;
				}else{
					return false;
				}
        		
        		
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
         }
 
        protected void onProgressUpdate(Integer... progress) {
        	super.onProgressUpdate(progress);
        	progressDialog.setMessage("Prefetching data..." + progress[0] + "/" + totalRecords);
        	 
        }
        
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            
            if(result){	
				
            	Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
				
				SharedPreferencesClass.setLocalSharedPreference(SplashActivity.this, "URL", spURL);
	            
				Intent mainActivity = new Intent(SplashActivity.this, SettingsActivity.class);
		        startActivity(mainActivity);
		        
			}else{
				
				Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();
				reCallActivity();
				
			}
            
           
        }
 
    }
    
    /**
     * 	 after download completed.
     */
	@Override
	public void onTaskCompleted(TaskType taskType, String result) {
		switch (taskType) {
		case DATABASENAME:
			
			new PrefetchData().execute(result);

			break;

		default:
			break;
		}
		
	}
	
	public void reCallActivity(){
		Intent mainActivity = new Intent(SplashActivity.this, SplashActivity.class);
		startActivity(mainActivity);
	}
}
